//公共工具类
CommonUtils = {
	// 注册命名空间
	// 例如 CommonUtils.regNamespace("com.et");
	regNamespace : function(name) {
		var arr = name.split(".");
		var ns = "";
		for (var i = 0; i < arr.length; i++) {
			if (i > 0)
				ns += ".";
			ns += arr[i];
			eval("if(typeof(" + ns + ") == 'undefined') " + ns
					+ " = new Object();");
		}
	}
}

CommonUtils.regNamespace("com.im.common");

// 常量
com.im.common.mda = {};

com.im.common.util = {
	// 正则表达式验证
	regExp : function(type, value) {
		var pattern;
		if (type == "phone") {
			pattern = /(1[3-9]\d{9}$)/;
			return pattern.test(value);
		} else if (type == "telphone") {
			// pattern = /^\d{3,4}-?\d{7,9}$/;
            pattern =  /^((0\d{2,3})-)(\d{7,8})?$/
			return pattern.test(value);
		} else if (type == "email") {
			pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
			return pattern.test(value);
		}

		return false;
	},

	aesEncrypt : function(data) {
		var key = CryptoJS.enc.Utf8.parse('1234567896543210');
		var iv = CryptoJS.enc.Utf8.parse(com.im.common.mda.AES_IV);
		var srcs = CryptoJS.enc.Utf8.parse(data);
		var encrypted = CryptoJS.AES.encrypt(srcs, key, {
			iv : iv,
			mode : CryptoJS.mode.CBC
		});
		return encrypted.toString();
	},

	aesDecrypt : function(data) {
		var key = CryptoJS.enc.Utf8.parse('1234567896543210');
		var iv = CryptoJS.enc.Utf8.parse(com.im.common.mda.AES_IV);
		var decrypt = CryptoJS.AES.decrypt(data, key, {
			iv : iv,
			mode : CryptoJS.mode.CBC
		});
		return CryptoJS.enc.Utf8.stringify(decrypt).toString();
	},
	aesDecryptIv : function(data,aesIv) {
		var key = CryptoJS.enc.Utf8.parse('1234567896543210');
		var iv = CryptoJS.enc.Utf8.parse(aesIv);
		var decrypt = CryptoJS.AES.decrypt(data, key, {
			iv : iv,
			mode : CryptoJS.mode.CBC
		});
		return CryptoJS.enc.Utf8.stringify(decrypt).toString();
	},
	postAsJson : function(url, param) {
		var result;
		$.post(url, param, function(data) {
			var res = JSON.parse(data);
			if (!(com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT === undefined)
					&& (com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT == 'Y')) {
				result = JSON.parse(com.im.common.util
						.aesDecrypt(res.encryptMsg));
			} else {
				result = data;
			}

			if (result.resultCode == '0') {
				result.success = true;
			} else {
				result.success = false;
			}
		});
		return result;
	},
	aesEncryptForSwitch : function(param) {
		if (!(com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT === undefined)
				&& (com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT == 'Y')) {
			var paramTo = {};
			paramTo.encryptMsg = com.im.common.util.aesEncrypt(JSON
					.stringify(param));
			param = JSON.stringify(paramTo);
		} else {
			param = JSON.stringify(param);
		}

		return param;
	},

	aesDecryptForSwitch : function(data) {
		if (!(com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT === undefined)
				&& (com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT == 'Y')) {
			result = JSON.parse(com.im.common.util.aesDecrypt(data.encryptMsg));
		} else {
			result = data;
		}

		return result;
	},

	// 日期字符串比较 传空表示当前时间
	compareDate : function(d1, d2) {
		var dt1;
		var dt2;
		if (d1 != null) {
			dt1 = new Date(d1.replace(/-/g, "\/"));
		} else {
			dt1 = new Date();
		}
		if (d2 != null) {
			dt2 = new Date(d2.replace(/-/g, "\/"));
		} else {
			dt2 = new Date();
		}
		if (dt1 > dt2) {
			return 1;
		} else if (dt1 == dt2) {
			return 0;
		} else {
			return -1;
		}
	},

	// 是否图片
	isImage : function(name) {
		var suffix = name.substring(name.lastIndexOf('.') + 1, name.length)
				.toUpperCase();
		if (suffix == "JPG" || suffix == "JPEG" || suffix == "PNG"
				|| suffix == "GIF") {
			return true;
		} else {
			return false;
		}
	},

	escapeTextArea : function(value) {
		value = value.replace(/[\r\n]/g, "<br/>");
		value = value.replace(/\s/g, "&nbsp;");
		return value;
	},

	descapeTextArea : function(value) {
		value = value.replace(/<br>/g, "\r\n");
		value = value.replace(/<br\/>/g, "\r\n");
		value = value.replace(/&nbsp;/g, " ");

		return value;
	}

};

com.im.common.ajax = function() {
	// 请求参数
	var helper = {
		types : {
			post : "post",
			get : "get"
		},
		modes : {
			sync : false,
			async : true,
		},
		timeout : 10000,
		context : "/InfoManageWeb/",
		dataType : "json",
		contentTypes : {
			xml : "text/xml; charset=UTF-8",
			json : "application/json; charset=UTF-8",
			text : "text/plain; charset=UTF-8"
		}
	}

	// 同步请求
	var _syncCallAsJson = function(url, param) {
		var result;
		try {
			$
					.ajax({
						type : helper.types.post,
						async : helper.modes.sync,
						timeout : helper.timeout,
						url : helper.context + url,
						data : param,
						dataType : helper.dataType,
						contentType : helper.contentTypes.json,
						success : function(data) {
							// 解密
							if (!(com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT === undefined)
									&& (com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT == 'Y')) {
								result = JSON.parse(com.im.common.util
										.aesDecrypt(data.encryptMsg));
							} else {
								result = data;
							}
							if (result.resultCode == '0') {
								result.success = true;
							} else {
								result.success = false;
							}
						},
						error : function(XMLHttpRequest, textStatus,
								errorThrown) {
							var resultText = XMLHttpRequest.responseText;
							result = {
								"success" : false,
								"resultCode" : "-1",
								"resultMsg" : errorThrown
							};
						}
					});
		} catch (e) {
			result = {
				"success" : false,
				"resultCode" : "-1",
				"resultMsg" : "获取后台服务异常!"
			};
		}
		return result;
	};

	// 异步请求
	var _asyncCallAsJson = function(url, param, callback,ifEn,aesIv) {
		try {
			$.ajax({
						type : helper.types.post,
						async : helper.modes.async,
						timeout : helper.timeout,
						url : helper.context + "/" + url,
						data : param,
						dataType : helper.dataType,
						contentType : helper.contentTypes.json,
						success : function(data) {
							var result;
							// 解密
							if (ifEn != undefined && ifEn == 'Y') {
								var rj = com.im.common.util.aesDecryptIv(data.encryptMsg,aesIv);
								result = JSON.parse(rj);
							} else {
								result = data;
							}
							if (result.resultCode == '0') {
								result.success = true;
							} else {
								result.success = false;
							}
							callback(result);
						},
						error : function(XMLHttpRequest, textStatus,
								errorThrown) {
							var resultText = XMLHttpRequest.responseText;
							var result = {
								"success" : false,
								"resultCode" : "-1",
								"resultMsg" : errorThrown
							};
							callback(result);
						}
					});
		} catch (e) {
			var result = {
				"success" : false,
				"resultCode" : "-1",
				"resultMsg" : "获取后台服务异常!"
			};
			callback(result);
		}
	};

	// 异步上传文件
	var _asyncCallAsFile = function(param, callback) {
		try {
			var formData = new FormData();
			// formData.append("file", param)
			for (var i = 0; i < param.length; i++) {
				formData.append("file" + i + "", param[i])
			}
			$.ajax({
				type : helper.types.post,
				async : helper.modes.async,
				url : "/etfilesystem/fileController/batchUploadFiles",
				data : formData,
				contentType : false,
				processData : false,
				success : function(data) {
					var result = JSON.parse(data);
					if (result.resultCode == '0') {
						result.success = true;
					} else {
						result.success = false;
					}
					callback(result);
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					var resultText = XMLHttpRequest.responseText;
					var result = {
						"success" : false,
						"resultCode" : "-1",
						"resultMsg" : errorThrown
					};
					callback(result);
				}
			});
		} catch (e) {
			var result = {
				"success" : false,
				"resultCode" : "-1",
				"resultMsg" : "获取后台服务异常!"
			};
			callback(result);
		}
	};

	return {
		// post请求， 没有callback的时候为同步调用
		// var client = new com.et.common.ajax();
		// var result = client.callAsJson(url, param);
		// client.callAsJson(url, param, callback);
		callAsJson : function(url, param, callback) {
			// 加密
			if (!(com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT === undefined)
					&& (com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT == 'Y')) {
				var paramTo = {};
				paramTo.encryptMsg = com.im.common.util.aesEncrypt(JSON
						.stringify(param));
				param = JSON.stringify(paramTo);
			} else {
				param = JSON.stringify(param);
			}
			if (!!callback) {
				return _asyncCallAsJson(url, param, callback,com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT,com.im.common.mda.AES_IV);
			} else {
				return _syncCallAsJson(url, param);
			}
		},

		callAsFile : function(param, callback) {
			return _asyncCallAsFile(param, callback);
		}
	}
};

// 上传文件组件
// 当前页面全部文件
var commonFiles = new Object();
com.im.common.file = function() {
	// 文件类型
	var oriFileBtnName;

	// 激活组件
	var _activate = function(type, oldFiles) {
		if (type == 2) {
			oriFileBtnName = "添加图片";
		} else {
			oriFileBtnName = "添加文件";
		}

		// 添加组件
		$("#common_file_bnt").text(oriFileBtnName);
		if ($("#common_file_name").size() == 0) {
			$("#common_file_bnt")
					.before(
							"<div id='common_file_src' style='display: none; margin:10px;'></div>");
			$("#common_file_bnt").after(
					"<div id='common_file_name' style='display: none;'></div>");
			if (type == 2) {
				$("#common_file_name")
						.after(
								"<input id='common_file' type='file' accept='image/*' multiple='multiple' style='display: none;'>");
			} else {
				$("#common_file_name")
						.after(
								"<input id='common_file' type='file' multiple='multiple' style='display: none;'>");
			}
			$("#common_file_bnt").click(function() {
				$("#common_file").click();
			});
			$("#common_file").change(function() {
				_add(this.files);
			});
		}

		// 清除数据
		commonFiles.newly = [];
		commonFiles.old = [];
		commonFiles.del = [];
		$("#common_file_name").children().remove();
		$("#common_file_src").children().remove();

		// 添加已有文件
		if (oldFiles != undefined && oldFiles.length > 0) {
			commonFiles.old = oldFiles;
			for (var i = 0; i < oldFiles.length; i++) {
				var fileId = "file_old_" + (i + commonFiles.old.length);
				var isImage = com.im.common.util.isImage(oldFiles[i].fileSuffix);
				var name = "";
				var src = "";
				if (isImage) {
					src += "<img class='"
							+ fileId
							+ "' id='"
							+ fileId
							//+ "' width='100px' height='100px' src='/etfilesystem/"
							+ "' width='100px' height='100px' src='/etfiles/"
							+ oldFiles[i].filePath + "'>";
					$("#common_file_src").append(src);
					if ($("#common_file_src").is(':hidden')) {
						$("#common_file_src").show();
					}
				}
				if (isImage) {
					name += "<br class='" + fileId + "'/><label class='"
							+ fileId + "'>" + oldFiles[i].uploadName
							+ "</label><a class='common_file_btn_del " + fileId
							+ "' fileId = '" + fileId + "'>删除附件</a>";
				} else {
					name += "<br class='"
							+ fileId
							+ "'/><a href='javascript:void(0);' class='common_file_btn_dwn "
							+ fileId + "' seq='" + i +"'>" + oldFiles[i].uploadName
							+ "</a> <a class='common_file_btn_del " + fileId
							+ "' fileId = '" + fileId + "'>删除附件</a>";
				}
				$("#common_file_name").append(name);
				if ($("#common_file_name").is(':hidden')) {
					$("#common_file_name").show();
					$("#common_file_bnt").text("继续添加");
				}
			}

			$(".common_file_btn_del").on("click", _del);
			$(".common_file_btn_dwn").on("click", _dwn);
		}

		return commonFiles;
	};

	// 添加附件
	var _add = function(files) {
		for (var i = 0; i < files.length; i++) {
			var need = true;

			for (var j = 0; j < commonFiles.newly.length; j++) {
				if (files[i].name == commonFiles.newly[j].name) {
					need = false;
					break;
				}
			}
			for (var j = 0; j < commonFiles.old.length; j++) {
				if (files[i].name == commonFiles.old[j].name) {
					need = false;
					break;
				}
			}

			if (!need) {
				continue;
			}

			commonFiles.newly.push(files[i]);

			var name = "";
			var src = "";
			var fileId = "file_new_" + (i + commonFiles.newly.length);
			var isImage = com.im.common.util.isImage(files[i].name);

			if (isImage) {
				var reder = new FileReader();
				reder.readAsDataURL(files[i]);
				reder.fid = fileId;
				src += "<img class='" + fileId + "' id='" + fileId
						+ "' width='100px' height='100px'>";
				$("#common_file_src").append(src);
				$(reder).load(function() {
					$('#' + this.fid).attr("src", this.result);
				})
				if ($("#common_file_src").is(':hidden')) {
					$("#common_file_src").show();
				}
			}
			name += "<br class='" + fileId + "'/><label class='" + fileId
					+ "'>" + files[i].name
					+ "</label> <a class='common_file_btn_del " + fileId
					+ "' fileId = '" + fileId + "'>删除附件</a>";
			$("#common_file_name").append(name);
			if ($("#common_file_name").is(':hidden')) {
				$("#common_file_name").show();
				$("#common_file_bnt").text("继续添加");
			}
		}

		$(".common_file_btn_del").on("click", _del);
	};

	var _del = function() {
		var name = $(this).prev().text();
		var fileId = $(this).attr("fileId");
		$("." + fileId).remove();

		for (var i = 0; i < commonFiles.newly.length; i++) {
			if (commonFiles.newly[i].name == name) {
				commonFiles.newly.splice(i, 1);
				i--;
			}
		}

		for (var i = 0; i < commonFiles.old.length; i++) {
			if (commonFiles.old[i].uploadName == name) {
				commonFiles.del.push(commonFiles.old[i]);
				commonFiles.old.splice(i, 1);
				i--;
			}
		}

		if (commonFiles.newly.length == 0 && commonFiles.old.length == 0) {
			$("#common_file_name").hide();
			$("#common_file_src").hide();
			$("#common_file_bnt").text(oriFileBtnName);
		}
		
		//移除文件时，清除文件选择框，避免不能重复选择同一个文件 yangwc 0711
		$("#common_file").val(''); 
	};

	var _dwn = function() {
		var seq = $(this).attr("seq");
		window.open('/etfilesystem/fileController/downloadFile?fileName='
				+ commonFiles.old[seq].filePath+'&realName='+encodeURI(commonFiles.old[seq].uploadName), '_blank');
	}

	return {
		// 入参：
		// type：1：文件、2：图片
		// oldFiles：可选，会显示已有文件，对象格式：同fileList
		// 返回：
		// 1： commonFiles.newly 新增的文件，对象格式：浏览器文件对象
		// 2：commonFiles.old 剩余未删除的老文件，对象格式：同fileList
		// 3：commonFiles.del 已删除的老文件，对象格式：同fileList
		activate : function(type, oldFiles) {
			return _activate(type, oldFiles);
		}
	}

};
com.im.common.request = function(){
	// 异步请求
	var _callAsPost = function(url, param, callback) {
		var result;
		try {
			$.post(url,param,function(data){
				if (!(com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT === undefined)
						&& (com.im.common.mda.SWITCH_AES_ENCRIPT_DECRIPT == 'Y')) {
					result = JSON.parse(com.im.common.util
							.aesDecrypt(JSON.parse(data).encryptMsg));
				}else{
					result = JSON.parse(data);
				}
				if(result.resultCode == 0){
					result.success = true;
				}else{
					result.success = false;
				}
				callback(result);
			});
		} catch (e) {
			result = {
				"success" : false,
				"resultCode" : "-1",
				"resultMsg" : "获取后台服务异常!"
			};
			callback(result);
		}
	};
	
	return{
		callAsPost : function(url,param, callback) {
			return _callAsPost(url,param, callback);
		}
	}
};

com.im.common.confirm= function(info,param,method){
  $.confirm({
    icon: 'fa fa-question-circle',
    title:info,
    type: 'blue',
    content: "",
    autoClose: 'cancel|8000',
    buttons: {
      cancel: {
        text: "取消",
        btnClass: 'btn-default',
        action: null
      },
      confirm: {
        text: "确定",
        btnClass: 'btn-primary',
        keys: ['enter', 'shift'],
        action: function () {
        	if(method!=null && method!=undefined)
          var  func=eval(method);
          new func(param);
        }
      }
    }
  });
};



var mainActiveId='home';
function locationUrl(url,activeId){
       if(mainActiveId != null  && mainActiveId != "" && activeId != null && activeId != ""){
         $("#"+mainActiveId).removeAttr("class");
         $("#"+activeId).attr("class", "active");
         mainActiveId = activeId;
       }
  goUrl(url,null);
}

var xmlhttp = new getXMLObject();

function goUrl(url,params) {
  fixUrl(url,params);
  if(xmlhttp) {
  	url="/InfoManageWeb/"+url;
    xmlhttp.open("POST",url,true);
    xmlhttp.onreadystatechange = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    xmlhttp.send(params);
    // with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://v3.jiathis.com/code_mini/jia.js?uid=2126448'];
  }
}


function getXMLObject() {
  var xmlHttp = false;
  try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft
    // Browsers
  } catch (e) {
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft
      // IE 6.0+
    } catch (e2) {
      xmlHttp = false // No Browser accepts the XMLHTTP Object then false
    }
  }
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest(); // For Mozilla, Opera Browsers
  }
  return xmlHttp; // Mandatory Statement returning the ajax object created
}

var firstUrl = null;
var secondUrl = null;
var flag=1;

function handleServerResponse() {
  if (xmlhttp.readyState == 4) {
    //document.getElementById("mainSection").innerHTML =xmlhttp.responseText;
    var text = xmlhttp.responseText;
    if(text.indexOf("<title>Favorites error Page</title>") >= 0){
      window.location.href="/error.html";
    }else{
      $("#content").html(xmlhttp.responseText);
    }
  }
}

function fixUrl(url, params){
  if(params != null){
    url = url + "?" + params;
  }
  if(firstUrl == null){
    firstUrl = url;
  }else if(secondUrl == null){
    secondUrl = url;
  }else{
    if(flag == 1){
      firstUrl = url;
      flag = 2;
    }else{
      secondUrl = url;
      flag = 1;
    }
  }
}

$(function(){
  toastr.options = {
    closeButton: true,
    debug: false,
    progressBar: true,
    positionClass: "toast-bottom-right",//"toast-bottom-full-width",//"toast-bottom-center",
    hideDuration: "1000",
    timeOut: "5000",
    extendedTimeOut: "1000",
    showEasing: "swing",
    hideEasing: "linear",
    showMethod: "fadeIn",
    hideMethod: "fadeOut"
  };
});